var app = getApp()
import ajaxhelper from '../../utils/ajaxhelper.js';
import { signByMd5 } from "../../utils/util";
import checkLogin from '../../utils/checkLogin.js';
// var starModule = require("../common/star/star.js");//五星评价
// var comment = require("../common/comment/comment.js");//评论
var payBtn = require('../common/payBtn/payBtn.js');
Page(Object.assign({}, payBtn,{
  data: {
    currentTab:1, //预设当前项的值
    isMoreIntro:false,//是否显示更多内容
    dataList: [],//列表数据
    hasRefresh: false,
    isGetMore: false,
    hasMore: true,
    pageSize: 15,
    pageNo: 1,
    isShow: false,//是否显示没有列表的提示图
    canView:false,//是否可以观看
    currentPlayId:'',//正在播放的资源id
    alePlayPrece:0,//播放进度百分比
    isSubscribe: false,//是否已订阅
    totalPrice: '',//购买价格
    canView:true,//默认可以观看
  },
  onLoad: function (options) {
    var that=this;
    var id=options.id||'';
    if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      console.log(scene);
      id = scene;
    }
    this.setData({
      id:id
    })
    // 检查有没有登录，第二个参数是回调函数
    // checkLogin.login(this, function (res) {
    //   console.log(res)
    //   this.getAllDetail();//获取详情页面数据
    // })
    // this.getAllDetail();//获取详情页面数据
  },
  onShow(){
    var that=this;
    // 检查有没有登录，第二个参数是回调函数
    checkLogin.login(this, function (res) {
      console.log(res)
      this.getAllDetail();//获取详情页面数据
    })
    if (!app.backgroundAudioManager.src){
      return false
    }
    this.checkPlay();
    // 获取全局音频信息
    var urlObj = wx.getStorageSync('gloalObjUrl');
    urlObj = urlObj ? JSON.parse(urlObj) : {};
    that.setData({
      urlObj,
      currentPlayId: urlObj.id,
      curPlayIndex: urlObj.index,//正在播放的序号
    })
    //音频结束
    app.backgroundAudioManager.onEnded(function () {
      that.setData({
        isPlay: false
      })
      // 获取全局音频信息 去缓存中取该资源是否付费
      var urlObj = wx.getStorageSync('gloalObjUrl');
      urlObj = urlObj ? JSON.parse(urlObj) : {};
      if (urlObj.canView){
        that.setData({
          canView:true
        })
      }
      that.playNextAudio()
    })
  },
  getAllDetail() {
    var id=this.data.id;
    var token = (wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token) || '';
    ajaxhelper.get(app.globalData.frontJSHost + 'knowledge/detailById/' + id + '?token=' + encodeURIComponent(token), {}, this, this.setAllDetail)
  },
  setAllDetail(res) {
    var that = this;
    if (res.result) {
      var indexList = res.data.indexList;
      if (indexList) {
        // 处理时间 数据
        var resourcesList=[]; //吧所有课程放到一个数组里面
        indexList.forEach(function (item, index, arr) {
          if (item.resources && item.resources.length > 0) {
            item.resources.forEach(function (itemRe, index, arr) {
              itemRe.lengthObj = app.timeFormat(itemRe.length);
              itemRe.createDate = new Date(+itemRe.createDate).format("yyyy-MM-dd hh:mm");
              resourcesList.push(itemRe);
            })
          }
        })
        res.data.resourcesList = resourcesList;
      }
      if (res.data.updateDate) {
        res.data.updateDate = new Date(+res.data.updateDate).format("yyyy年MM月dd日");
      }
      if (res.data.statistics){
        res.data.statistics.avgPoint = res.data.statistics.avgPoint && res.data.statistics.avgPoint.toFixed(1);///保留一位小数
      }
      that.setData({
        lecturers: res.data.lecturers,//讲师
        course: res.data.course,//视频简介介绍
        indexList: res.data.indexList,//视频列表
        statistics: res.data.statistics,//评分评论
        subject: res.data.subject,//分类
        canView: res.data.canView,//是否可以播放
        resourcesList:res.data.resourcesList,//处理好的资源列表
        favoriteCount: res.data.favoriteCount,//订阅的个数
        isSubscribe:res.data.favoriteStatus,//是否订阅
        chapterCount: res.data.chapterCount,//总共集数
        updateDate: res.data.updateDate,//更新日期
        totalPrice: res.data.course.currentPrice,//购买价格
      })
      //吧处理好的数据存储 转入详情时候使用
      // var allAudioDetail = JSON.stringify(res.data);
      // wx.setStorage({
      //   key: 'allAudioDetail',
      //   data: allAudioDetail,
      // })
    } else {
      wx.showToast({
        title: !!res.message.global ? res.message.global : "请求出错",
        icon: "loading"
      })
    }
  },
  //下拉刷新
  onPullDownRefresh() {
  },
  //上拉加载
  onReachBottom() {
    
  },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.currentTarget.dataset.current;
    if (this.data.currentTab == cur) { return false; }
    else {
      this.setData({
        currentTab: cur
      })
    }
  },
  // 是否展示全部内容
  isMoreIntro(){
    if (this.data.isMoreIntro){
      this.setData({
        isMoreIntro:false
      })
    }else{
      this.setData({
        isMoreIntro: true
      })
    }
  },
  // 音频播放详情
  goAudioPlayDetail(e){
    console.log(e)
    var that=this;
    // if (this.data.canView){
      var url = e.currentTarget.dataset.url;
      var id = e.currentTarget.dataset.resourceId;//课程中资源id
      var courseId = e.currentTarget.dataset.courseId;//课程id
      var index = e.currentTarget.dataset.index;//课程序号
      var cover = e.currentTarget.dataset.cover;//资源封面
      var resourceItem = e.currentTarget.dataset.resourceItem;//资源全部信息
      var lecturers = e.currentTarget.dataset.lecturers;//导师
      var obj = {
        url,
        id,
        courseId,
        index,
        cover,
        resourceItem,
        lecturers
      }
      if (!that.data.canView && !url) {
        // wx.showToast({
        //   title: '请购买视听',
        //   icon: 'loading'
        // })
        //改为弹窗购买链接
        wx.showModal({
          title: '提示',
          content: '请购买该资源',
          confirmColor: '#FF4612',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              that.goPay();//购买
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return false;
      }
      if (that.data.canView && !url) {
        wx.showToast({
          title: '资源地址有误，请确认',
          icon: 'loading'
        })
        return false;
      }
      // 存储要播放的urlobj
      wx.setStorage({
        key: 'gloalObjUrl',
        data: JSON.stringify(obj) ,
      })
      
      that.setData({
        urlObj: obj,
        currentPlayId:id,
        curPlayIndex: index
      })
      wx.navigateTo({
        url: '../audioPlayDetail/audioPlayDetail?urlObj=' + JSON.stringify(obj),
      })
      
      //播放统计
      app.addHit(id, 'RESOURCE_AUDIO');
    // }else{
    //   wx.showToast({
    //     title: '请先购买该视频',
    //   })
    // }
  },
  // 查看更多评价
  lookAllComment(){
    console.log(4)
    wx.navigateTo({
      url: '../commentList/commentList',
    })
  },
  // 转换文稿
  goText(e) {
    console.log(e)
    var snapshotFlag = e.currentTarget.dataset.snapshotFlag;//是否可以试听
    if (this.data.canView || (!this.data.canView && snapshotFlag)){
      var id = e.currentTarget.dataset.resourceId;//课程中资源id
      var courseId = e.currentTarget.dataset.courseId;//课程id
      var articleId = e.currentTarget.dataset.articleId;//文稿id
      if (articleId) {
        wx.navigateTo({
          url: '../text/text?articleId=' + articleId,
        })
      } else {
        wx.showToast({
          title: '该资源没有文稿',
          icon: 'loading'
        })
      }
    }else{
      wx.showToast({
        title: '请先购买该资源',
        icon:'loading'
      })
    }
  },
  // 全局检测有没有背景音乐
  checkPlay() {
    var that = this;
    var duration, currentTime, alePlayPrece;
    var backgroundAudioManager = app.backgroundAudioManager;
    if (backgroundAudioManager.paused == undefined){
      return false
    }
    // 背景音乐正在播放  backgroundAudioManager.paused!=undefiend的目的是为了检测第一次播放音乐
    if (!backgroundAudioManager.paused && backgroundAudioManager.paused != undefined) {
      that.setData({
        isPlay: true
      })
      
    } else if (backgroundAudioManager.paused) {  //在暂停 checkPlayList判断是否是前一首下一首 如果为true意思就是重新获取url
      that.setData({
        isPlay: false
      })
    }
    backgroundAudioManager.onError(function () {
      that.setData({
        isPlay: false
      })

    })
    backgroundAudioManager.onTimeUpdate(function () {
      duration = Math.ceil(backgroundAudioManager.duration);
      currentTime = Math.ceil(backgroundAudioManager.currentTime)
      alePlayPrece = parseInt((currentTime / duration * 100)) || 0;
      that.setData({
        alePlayPrece
      })
      // console.log('专辑音频' + currentTime);
      that.timeupdateCount(backgroundAudioManager.currentTime, backgroundAudioManager.duration)
    })
  },
  // 点击播放的图片控制播放
  controlPlayItem(e){
    var that = this;
    // if (this.data.canView){
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.resourceId;//课程中资源id
    var courseId = e.currentTarget.dataset.courseId;//课程id
    var index = e.currentTarget.dataset.index;//课程序号
    var cover = e.currentTarget.dataset.cover;//资源封面
    var resourceItem = e.currentTarget.dataset.resourceItem;//资源全部信息
    var lecturers = e.currentTarget.dataset.lecturers;//导师
    var obj = {
      url,
      id,
      courseId,
      index,
      cover,
      resourceItem,
      lecturers
    }
    if (!that.data.canView && !url) {
      // wx.showToast({
      //   title: '请购买视听',
      //   icon: 'loading'
      // })
      //改为弹窗购买链接
      wx.showModal({
        title: '提示',
        content: '请购买该资源',
        confirmColor: '#FF4612',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            that.goPay();//购买
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    }
    if (that.data.canView && !url) {
      wx.showToast({
        title: '资源地址有误，请确认',
        icon: 'loading'
      })
      return false;
    }
    // 存储要播放的urlobj
    wx.setStorage({
      key: 'gloalObjUrl',
      data: JSON.stringify(obj),
    })
    
    that.setData({
      urlObj: obj,
      currentPlayId: id,
      playUrl: url,
      curPlayIndex:index
    })
    that.play();
    //播放统计
    app.addHit(id, 'RESOURCE_AUDIO');
    
  },
  // 播放
  play: function () {
    var that = this, duration = that.data.duration, currentTime = that.data.currentTime;
    var currUrl = app.backgroundAudioManager.src;
    var backgroundAudioManager = app.backgroundAudioManager;
    // that.setData({
    //   isPlay: false
    // })
    if (!that.data.canView && !that.data.playUrl){
      wx.showToast({
        title: '请购买视听',
        icon: 'loading'
      })
      // that.setData({
      //   alePlayPrece: 0
      // })
      return false;
    }
    if (!that.data.playUrl) {
      wx.showToast({
        title: '资源地址有误，请确认',
        icon: 'loading'
      })
      // that.setData({
      //   alePlayPrece: 0
      // })
      return false;
    }
    if ((currUrl && currUrl != that.data.playUrl) || !currUrl) {
      backgroundAudioManager.stop();
      backgroundAudioManager.src = that.data.playUrl;
      backgroundAudioManager.title = '结果大学'
      backgroundAudioManager.epname = '课程';
      backgroundAudioManager.singer = '结果大学';
      backgroundAudioManager.play();
      // backgroundAudioManager.title = '此时此刻'
      // backgroundAudioManager.epname = '此时此刻'
      // backgroundAudioManager.singer = '汪峰'
      that.setData({
        isPlay: true
      })
     
    } else if (currUrl && currUrl == that.data.playUrl) {
      if (that.data.isPlay){
        that.pauseAudio();
      }else{
        that.playAudio()
      }
      
    } 
    backgroundAudioManager.onEnded(function () {
      that.setData({
        isPlay: false
      })
      // 获取全局音频信息 去缓存中取该资源是否付费
      var urlObj = wx.getStorageSync('gloalObjUrl');
      urlObj = urlObj ? JSON.parse(urlObj) : {};
      if (urlObj.canView) {
        that.setData({
          canView: true
        })
      }
      that.playNextAudio()
    })
    backgroundAudioManager.onError(function () {
      that.setData({
        isPlay: false
      })

    })
    backgroundAudioManager.onTimeUpdate(function () {
      duration = Math.ceil(backgroundAudioManager.duration);
      currentTime = Math.ceil(backgroundAudioManager.currentTime)
      var alePlayPrece = parseInt((currentTime / duration * 100)) || 0;
      that.setData({
        alePlayPrece
      })
      // console.log('专辑音频' + currentTime);
      that.timeupdateCount(backgroundAudioManager.currentTime, backgroundAudioManager.duration)
    })

  },
  // 暂停播放
  pauseAudio() {
    console.log(1111)
    this.setData({
      isPlay: false
    })
    app.backgroundAudioManager.pause();
  },
  // 继续播放
  playAudio() {
    this.setData({
      isPlay: true
    })
    app.backgroundAudioManager.play();
  },
  // 播放下一首
  playNextAudio() {
    var that = this;
    if (that.data.curPlayIndex == that.data.resourcesList.length - 1) {
      wx.showToast({
        title: '已经是最后一首喽',
        icon: 'loading'
      })
    } else {
      // 获取下一首的地址
      // 判断是否为试听试看
      var curPlayIndex = that.data.curPlayIndex + 1;
      var resourcesItem = that.data.resourcesList[curPlayIndex];
      // (canView || (!canView && resourceItem.snapshotFlag)) ? resourceItem.url : ''
      var url = (that.data.canView || (!that.data.canView && resourcesItem.snapshotFlag)) ? resourcesItem.url :'';///////////视频地址是试听地址还是正式地址
      var id = resourcesItem.id;//课程中资源id
      var courseId = resourcesItem.courseId;//课程id
      var index = curPlayIndex;//课程序号
      var cover = resourcesItem.cover;//资源封面
      var resourceItem = resourcesItem;//资源全部信息
      var lecturers = that.data.lecturers;//导师
      var obj = {
        url,
        id,
        courseId,
        index,
        cover,
        resourceItem,
        lecturers
      }
     
      // 存储要播放的urlobj
      wx.setStorage({
        key: 'gloalObjUrl',
        data: JSON.stringify(obj),
      })
      
      that.setData({
        curPlayIndex: curPlayIndex,
        playUrl: url,
        currentPlayId: id,

      })
      if (!that.data.canView && !url) {
        wx.showToast({
          title: '请购买视听',
          icon: 'loading'
        })
        that.setData({
          alePlayPrece:0
        })
        return false;
      }
      if (that.data.canView && !url) {
        wx.showToast({
          title: '资源地址有误，请确认',
          icon: 'loading'
        })
        that.setData({
          alePlayPrece: 0
        })
        return false;
      }
      that.play()//调用播放
      //播放统计
      app.addHit(id, 'RESOURCE_AUDIO');
    }
  },
  // 订阅
  goSubscribe(e) {
    var id = e.currentTarget.dataset.courseId;
    var type = e.currentTarget.dataset.type;
    var token = (wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token) || '';
    if (this.data.isSubscribe) {
      // wx.showToast({
      //   title: '已经订阅过',
      //   icon: 'loading'
      // })
      // return false   
      var param = {
        "ids": [id],
        "sourceType": type,
        // "token": token
      }
      ajaxhelper.post(app.globalData.frontJSHost + 'favorite/delete?token=' +encodeURIComponent(token), param, this, function (res) {
        console.log(res)
        var that = this;
        if (res.result) {
          that.setData({
            isSubscribe: false,
          })
          // wx.showModal({
          //   title: '已取消订阅！',
          //   content: '你可以点击订阅按钮再次订阅',
          //   showCancel: false,
          //   confirmText: '知道了',
          //   confirmColor: '#FF4612',
          //   success: function (res) {
          //   }
          // })
          wx.showToast({
            title: '已取消订阅',
            // icon:'loading'
          })
        } else {
          //有状态值再更改
          if (res.message.global =='您已取消收藏'){
            that.setData({
              isSubscribe: false,
            })
          }
          wx.showToast({
            title: !!res.message.global ? res.message.global : "请求出错",
            icon: "loading"
          })
        }
      })
    }else{
      var param = {
        "sourceId": id,
        "sourceType": type
      }
      ajaxhelper.post(app.globalData.frontJSHost + 'favorite/add?token=' +encodeURIComponent(token), param, this, function (res) {
        console.log(res)
        var that = this;
        if (res.result) {
          //代表已经订阅过 然后又去掉的这个add这个接口
          if (res.data==0){
            wx.showToast({
              title: '已经订阅过',
              icon:'loading'
            })
          }else{
            // wx.showModal({
            //   title: '订阅成功！',
            //   content: '你可以在“订阅”中查看',
            //   showCancel: false,
            //   confirmText: '知道了',
            //   confirmColor: '#FF4612',
            //   success: function (res) {
            //   }
            // })
            wx.showToast({
              title: '订阅成功',
              // icon: 'loading'
            })
          }
          that.setData({
            isSubscribe: true,
          })
        } else {
          wx.showToast({
            title: !!res.message.global ? res.message.global : "请求出错",
            icon: "loading"
          })
        }
      })
    }
    
    
  },
  // 购买
  // goPay(e) {
  //   var that = this;
  //   // var courseItem = e.currentTarget.dataset.courseItem;
  //   /////////////
  //   // var coverMain = e.currentTarget.dataset.cover;
  //   // var name = e.currentTarget.dataset.name;
  //   // var currentPrice = e.currentTarget.dataset.price;
  //   // var updateDate = e.currentTarget.dataset.update;
  //   // var chapterCount = e.currentTarget.dataset.chapterCount || 0;//总共集数
  //   // var mediaType = e.currentTarget.dataset.mediaType;//类型
  //   // var id = e.currentTarget.dataset.sourceId;//资源id
  //   //////////
  //   var coverMain = that.data.course.coverMain;
  //   var name = that.data.course.name;
  //   var currentPrice = that.data.course.currentPrice;
  //   var updateDate = that.data.updateDate;
  //   var chapterCount = that.data.chapterCount || 0;//总共集数
  //   var mediaType = that.data.course.mediaType;//类型
  //   var id = that.data.course.id;//资源id
  //   var courseItem = {
  //     coverMain,
  //     name,
  //     currentPrice,
  //     updateDate,
  //     chapterCount,
  //     mediaType,
  //     id
  //   }
  //   courseItem = JSON.stringify(courseItem);
  //   wx.navigateTo({
  //     url: '../pay/pay?courseItem=' + courseItem,
  //   })
  // },
  // 分享
  onShareAppMessage: function (res) {
    var cover = this.data.course.coverMain || 'http://image.chuangchuang.cn/chuangchuang/cc_other/20171221/20171221_1513820857788.jpg';
    var title = this.data.course.name || '';
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: title,
      path: '/pages/audioAlbumDetail/audioAlbumDetail?id=' + this.data.id,
      // imageUrl: cover,//测试 使用截图
      success: function (res) {
        // 转发成功
        console.log(res)
      },
      fail: function (res) {
        // 转发失败
        console.log(res)
      }
    }
  },
  // 播放进度变化
  timeupdateCount(currentTime, duration) {
    // console.log(currentTime);
    var currentTime = currentTime;
    var duration = duration;
    if ((currentTime - 10) > -0.1 && (currentTime - 10) < 0.25) {
      var curPlayIndex = this.data.curPlayIndex;
      var sourceId = this.data.resourcesList[curPlayIndex].id;
      app.playTimeCount(sourceId, 'RESOURCE_AUDIO', 'PLAY_10S');

    } else if ((currentTime - 3 * 60) > -0.1 && (currentTime - 3 * 60) < 0.25) {
      var curPlayIndex = this.data.curPlayIndex;
      var sourceId = this.data.resourcesList[curPlayIndex].id;
      app.playTimeCount(sourceId, 'RESOURCE_AUDIO', 'PLAY_3M');
    } else if ((currentTime - duration * 0.85) >= 0 && (currentTime - duration * 0.85) <= 0.5) {
      var curPlayIndex = this.data.curPlayIndex;
      var sourceId = this.data.resourcesList[curPlayIndex].id;
      app.playTimeCount(sourceId, 'RESOURCE_AUDIO', 'PLAY_END');
    }
  },
  // 生成海报页面
  goPoster(){
    var cover = this.data.course.coverMain;
    var title = this.data.course.name || '';
    var id = this.data.course.id;
    // var description = this.data.course.description
    var getUserInfo = wx.getStorageSync('getUserInfo');
    var mediaType = this.data.course.mediaType;
    if (getUserInfo) {
      var userName = getUserInfo.nickName;
      var avatarUrl = getUserInfo.avatarUrl;
    } 
    wx.navigateTo({
      url: '../notice/notice?cover=' + cover + '&title=' + title + '&id=' + id + '&userName=' + userName + '&avatarUrl=' + avatarUrl + '&mediaType=' + mediaType,
    })
  }
}))
